<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Apply extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();
        $this->load->model('MPayRequest');
        $this->load->model('MAdmin');
        $this->load->model('MShop');

        $allShops = $this->MShop->getAllShopsTrue();
        $allReviewsAdmin = $this->MAdmin->getAllReviewsAdmin();//所有测评人
        $allFinance = $this->MAdmin->getAllFanceAdmin();
        $this->_validation = Array(
            array('field' => 'finance_id', 'label' => '处理改申请记录的财务ID', 'rules' => 'integer')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        , array('field' => 'pay_image', 'label' => '附加图', 'rules' => '')
        , array('field' => 'pay_image_1', 'label' => '附加图1', 'rules' => '')
        , array('field' => 'pay_image_2', 'label' => '附加图2', 'rules' => '')
        , array('field' => 'pay_image_3', 'label' => '附加图3', 'rules' => '')
        , array('field' => 'pay_image_4', 'label' => '附加图4', 'rules' => '')
        , array('field' => 'pay_image_5', 'label' => '附加图5', 'rules' => '')
        );

        $this->assign('allShops', $allShops);
        $this->assign('allReviewsAdmin', $allReviewsAdmin);
        $this->assign('allFinance', $allFinance);
    }

    function index()
    {
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('submiter_id', 'where');
        $this->formfilter->addFilter('finance_id', 'where');
        $this->formfilter->addFilter('status', 'where');

        // create_time
        if ($begintime = filterValue('pay_request_create_time_begin')) {
            $this->formfilter->addFilter('pay_request_create_time_begin', 'where', array('create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('pay_request_create_time_end')) {
            $this->formfilter->addFilter('pay_request_create_time_end', 'where', array('create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        // update_time
        if ($begintime = filterValue('pay_request_update_time_begin')) {
            $this->formfilter->addFilter('pay_request_update_time_begin', 'where', array('update_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('pay_request_update_time_end')) {
            $this->formfilter->addFilter('pay_request_update_time_end', 'where', array('update_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('payrequest_number_perpage');
        $total_number = $this->MPayRequest->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MPayRequest->getList($limit);
        $this->assign('total_number', $total_number);

        //获取当前数据的统计信息
        $listStatic = $this->MPayRequest->getListStatic();
        $ids = array();
        if (count($listStatic)){
            foreach ($listStatic as $v){
                $ids[] = $v->id;
            }
        }
        $this->assign('list', $list);
        $this->layout();
    }

    public function detail($id)
    {
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->load->model('MTaskRecordItem');
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MPayRequest->getById($id);
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }

        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());

            $this->db->trans_start();
            //此处保存时需要检查不同合并付款类型条件下对其下测评记录状态和财务申请记录状态进行更改、
            if (!$this->MTaskRecordItem->updateAllItemStatusByPayRequestID($id, $this->_user->id)) {
                $this->db->_trans_status = FALSE;
            }
            //修改当前记录状态为已完成
            $newObj->status = 1;

            //粘贴的图片
            if (!file_exists('upload/parseimg/')){
                if (!mkdir('upload/parseimg/', DIR_WRITE_MODE,true)) {
                    echo json_encode(Array('error' => 'upload/parseimg/'));
                    return;
                }
            }
            if ($this->input->post('pay_image')) {
                $pay_image = $this->input->post('pay_image');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $pay_image, $result)){
                    $type = $result[2];
                    $new_file = "upload/parseimg/".md5(uniqid(time()).uniqid(time())).".{$type}";
                    file_put_contents($new_file, base64_decode(str_replace($result[1], '', $pay_image)));
                }
                $newObj->pay_image = $new_file;
            }
            if ($this->input->post('pay_image_1')){
                $pay_image_1 = $this->input->post('pay_image_1');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $pay_image_1, $result1)){
                    $type1 = $result1[2];

                    $new_file1 = "upload/parseimg/".md5(uniqid(time()).uniqid(time())).".{$type1}";
                    file_put_contents($new_file1, base64_decode(str_replace($result1[1], '', $pay_image_1)));
                }
                $newObj->pay_image_1 = $new_file1;
            }
            if ($this->input->post('pay_image_2')){
                $pay_image_2 = $this->input->post('pay_image_2');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $pay_image_2, $result2)){
                    $type2 = $result2[2];

                    $new_file2 = "upload/parseimg/".md5(uniqid(time()).uniqid(time())).".{$type2}";
                    file_put_contents($new_file2, base64_decode(str_replace($result2[1], '', $pay_image_2)));
                }
                $newObj->pay_image_2 = $new_file2;
            }

            if (!$this->MPayRequest->update($newObj)) {
                $this->db->_trans_status = FALSE;
            }
            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                successAndRedirect(l('edit_success'));
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }
        //获取当前财务申请对应的所有测评记录
        $this->load->model('MTaskRecordItem');
        $list = $this->MTaskRecordItem->getFinanceList($obj->id);
        $this->load->model('MPayAccount');
        $allAccount = $this->MPayAccount->getAllAvailableAccount();

        $this->assign('allAccount', $allAccount);
        $this->assign('detail', $obj);
        $this->assign('list', $list);
        $this->layout('detail');
    }

    function add()
    {
        $this->load->model('MTaskRecordItem');
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->load->library('form_validation');
        $this->load->library('session');
        $this->form_validation->set_rules($this->_validation);

        //从session中取前步提交的ids
        $ids = $this->session->userdata('PAY_REQUEST_CEPING_IDS');
        if(!$ids){
            errorAndRedirect('选中的记录款项已失效或还未选中，请重新选择！', 'tasks/taskrecorditem');
        }
        $ids = implode(',', $ids);
        $this->session->set_userdata('ids', $ids);

        $limit = $this->pagination($this->MTaskRecordItem->getCount($ids));
        $list = $this->MTaskRecordItem->getList($limit, $ids);
        $obj = $this->MPayRequest->createVo();

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->submiter_id = $this->_user->id;

            //粘贴的图片
            if (!file_exists('upload/parseimg/')){
                if (!mkdir('upload/parseimg/', DIR_WRITE_MODE,true)) {
                    echo json_encode(Array('error' => 'upload/parseimg/'));
                    return;
                }
            }
            if ($this->input->post('pay_image')) {
                $pay_image = $this->input->post('pay_image');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $pay_image, $result)){
                    $type = $result[2];
                    $new_file = "upload/parseimg/".md5(uniqid(time()).uniqid(time())).".{$type}";
                    file_put_contents($new_file, base64_decode(str_replace($result[1], '', $pay_image)));
                }
                $newObj->pay_image = $new_file;
            }
            if ($this->input->post('pay_image_1')){
                $pay_image_1 = $this->input->post('pay_image_1');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $pay_image_1, $result1)){
                    $type1 = $result1[2];

                    $new_file1 = "upload/parseimg/".md5(uniqid(time()).uniqid(time())).".{$type1}";
                    file_put_contents($new_file1, base64_decode(str_replace($result1[1], '', $pay_image_1)));
                }
                $newObj->pay_image_1 = $new_file1;
            }
            if ($this->input->post('pay_image_2')){
                $pay_image_2 = $this->input->post('pay_image_2');
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $pay_image_2, $result2)){
                    $type2 = $result2[2];

                    $new_file2 = "upload/parseimg/".md5(uniqid(time()).uniqid(time())).".{$type2}";
                    file_put_contents($new_file2, base64_decode(str_replace($result2[1], '', $pay_image_2)));
                }
                $newObj->pay_image_2 = $new_file2;
            }

            if ($this->input->post('pay_image_3')) {
                $obj->pay_image_3 = $this->input->post('pay_image_3');
            }
            if ($this->input->post('pay_image_4')) {
                $obj->pay_image_4 = $this->input->post('pay_image_4');
            }
            if ($this->input->post('pay_image_5')) {
                $obj->pay_image_5 = $this->input->post('pay_image_5');
            }

            //事务处理
            $this->db->trans_start();
            $result = $this->MPayRequest->add($newObj);
            if (!$result) {
                $this->db->_trans_status = FALSE;
            }

            //更新操作记录与财务申请的关系
            $ids_arr = explode(',', $ids);
            $arr = [];
            foreach ($ids_arr as $v) {
                $item['id'] = $v;
                $item['pay_request_id'] = $result;
                $item['status'] = 1;    //提交的状态统一改为1=》财务待处理
                $arr[] = $item;
                $this->MTaskRecordItem->update((object)$item);
            }

            $this->db->trans_complete();

            //将session内容清空
            $this->session->set_userdata('PAY_REQUEST_CEPING_IDS',null);

            if ($this->db->trans_status() !== FALSE) {
                successAndRedirect(l('add_success'), 'finance/apply/');
            } else {
                errorAndRedirect(l('add_error'), 'finance/apply/add');
            }
        }
        $this->assign('obj', $obj);
        $this->assign('list', $list);
        $this->layout();
    }

    function edit($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MPayRequest->getOne(Array('id' => $id));

        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        $this->load->model('MTaskOperate');

        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        //获取当前财务申请对应的所有测评记录
        $list = $this->MTaskOperate->getAll(array('pay_request_id' => $obj->id));

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            if ($newObj->status == 3) {   //如果编辑时当前状态是财务标识为3=》申请记录信息有误,测评此时编辑时状态改为4=》测评修改后重新提交
                $newObj->status = 4;
            }
            $result = $this->MPayRequest->update($newObj);
            if ($result) {
                successAndRedirect(l('edit_success'), 'finance/apply/');
            } else {
                errorAndRedirect(l('edit_error'));
            }
        }
        $this->assign('obj', $obj);
        $this->assign('list', $list);
        $this->layout();
    }


    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MShop->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    function ajaxChange()
    {
        $request_id = $this->input->post('pay_request_id');
        $list = $this->MAdmin->getAllFanceAdmin();
        $return = [
            'request_id' => $request_id,
            'data' => $list
        ];
        exit(json_encode($return));
    }

    function ajaxEdit()
    {
        $request_id = $this->input->post('requestid');
        $finance_id = $this->input->post('id');
        $result = $this->MPayRequest->changeFinance($request_id, $finance_id);
        if ($result) {
            $return = [
                'status' => 1,
                'msg' => '修改成功'
            ];
        } else {
            $return = [
                'status' => 0,
                'msg' => '未修改'
            ];
        }
        exit(json_encode($return));
    }

    function changeRequestInfo($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MPayRequest->getOne(Array('id' => $id));

        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        $this->load->model('MTaskOperate');
        $this->load->helper('populate');
//        var_export($this->input->post()['new_pay_image_2']);
//        exit();
        $newObj = populate((Object)((Array)$obj), $this->input->post());
        if ($newObj->status == 3) {   //如果编辑时当前状态是财务标识为3=》申请记录信息有误,测评此时编辑时状态改为4=》测评修改后重新提交
            $newObj->status = 4;
        }
        $newObj->pay_image = $this->input->post()['new_pay_image'];
        $newObj->pay_image_1 = $this->input->post()['new_pay_image_1'];
        $newObj->pay_image_2 = $this->input->post()['new_pay_image_2'];
        $newObj->pay_image_3 = $this->input->post()['new_pay_image_3'];
        $newObj->pay_image_4 = $this->input->post()['new_pay_image_4'];
        $newObj->pay_image_5 = $this->input->post()['new_pay_image_5'];

        $result = $this->MPayRequest->update($newObj);
        if ($result) {
            successAndRedirect(l('edit_success'), site_url('finance/apply/index'));
        } else {
            errorAndRedirect(l('edit_error'));
        }
    }
}
